package com.pictureBook.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.pictureBook.merchant.config.JwtConfigProperties;
import com.pictureBook.merchant.entity.StoreAdmin;
import com.pictureBook.merchant.service.IStoreAdminService;
import com.pictureBook.merchant.utils.JWTUtils;
import com.pictureBook.merchant.utils.JwtInterceptor;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/1/6 14:01
 */
@CrossOrigin
@RestController
@Api("登录控制器")
@RequestMapping("/")
public class LoginController {

    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @Resource
    private IStoreAdminService iStoreAdminService;



    @PostMapping("/login")
    @ResponseBody
    public JSONObject login(@RequestBody JSONObject data){
        String username = String.valueOf(data.get("username"));
        String password = String.valueOf(data.get("password"));
        JSONObject jsonObject = new JSONObject();
        Map<String,Object> user = iStoreAdminService.login(username,password);
        if (user!=null){
            // 登录成功，返回token
            jsonObject.put("msg","登录成功");
            jsonObject.put("code",200);
            JSONObject jsonTemp = new JSONObject();
            jsonTemp.put("token", JWTUtils.sign(String.valueOf(user.get("user_id")),jwtConfigProperties));
            user.remove("main_store_id");
            jsonTemp.put("userInfo",user);
            jsonObject.put("data",jsonTemp);
        }else {
            jsonObject.put("msg","登陆失败，用户名或密码错误");
            jsonObject.put("code",500);
        }
        return jsonObject;
    }

    @GetMapping("/logout")
    @ResponseBody
    public JSONObject logout(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg","success");
        jsonObject.put("code",200);
        return jsonObject;
    }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public JSONObject getUserInfo(){
        Integer uId = Integer.parseInt(JWTUtils.getUserId(JwtInterceptor.getTokenInfo()));
        JSONObject jsonObject = new JSONObject();
        Map<String,Object> userInfo = iStoreAdminService.getUserInfoById(uId);
        if (userInfo!=null){
            // 登录成功，返回token
            jsonObject.put("msg","获取成功");
            jsonObject.put("code",200);
            JSONObject jsonTemp = new JSONObject();
            userInfo.remove("main_store_id");
            jsonTemp.put("userInfo",userInfo);
            jsonObject.put("data",jsonTemp);
        }else {
            jsonObject.put("msg","获取失败");
            jsonObject.put("code",500);
        }
        return jsonObject;
    }

}
